# Author:Li
import re
from django import forms
from apps.operations.models import UserAsk


# class AddAskForm2(forms.Form):
#     name = forms.CharField(required=True, min_length=2, max_length=20)
#     mobile = forms.CharField(required=True, min_length=11, max_length=11)
#     course_name = forms.CharField(required=True, min_length=2, max_length=20)


class AddAskForm(forms.ModelForm):
    # ModelForm基于模型生成的表单
    mobile = forms.CharField(max_length=11, min_length=11, required=True)

    class Meta:
        model = UserAsk
        # 映射UserAsk模型
        fields = ["name", "mobile", "course_name"]
        # 生成表单的字段

    def clean_mobile(self):
        """验证手机号码是否合法"""
        mobile = self.cleaned_data["mobile"]
        regex_mobile = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        p = re.compile(regex_mobile)
        if p.match(mobile):
            return mobile
        else:
            raise forms.ValidationError("手机号码非法", code="mobile_invalid")
